package com.ramos.kuaixiao.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.ramos.kuaixiao.App;
import com.ramos.kuaixiao.R;
import com.ramos.kuaixiao.db.AllCustomerDB;
import com.ramos.kuaixiao.db.AllCustomerStoreDB;
import com.ramos.kuaixiao.db.BrandDB;
import com.ramos.kuaixiao.db.BrandInfoDB;
import com.ramos.kuaixiao.db.ClientPriceDB;
import com.ramos.kuaixiao.db.CustomerDB;
import com.ramos.kuaixiao.db.CustomerStoreDB;
import com.ramos.kuaixiao.db.CustomerWareHouseDB;
import com.ramos.kuaixiao.db.EmpBrandDB;
import com.ramos.kuaixiao.db.EmpStoreHouseDB;
import com.ramos.kuaixiao.db.OrderDB;
import com.ramos.kuaixiao.db.PriceDB;
import com.ramos.kuaixiao.db.PriceTypeDB;
import com.ramos.kuaixiao.db.SaleCustomerDB;
import com.ramos.kuaixiao.db.SaleCustomerStoreDB;
import com.ramos.kuaixiao.db.ShopsDB;
import com.ramos.kuaixiao.db.StoreNumDB;
import com.ramos.kuaixiao.db.UnSubmitOrderDB;
import com.ramos.kuaixiao.db.WareHouseDB;
import com.ramos.kuaixiao.driver.ui.DriverMainActivity;
import com.ramos.kuaixiao.shops.ui.OrderMainActivity;
import com.ramos.kuaixiao.utils.CommUtil;
import com.ramos.kuaixiao.utils.CommonLoading;
import com.ramos.kuaixiao.utils.NetUtils;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StartLocation;
import com.ramos.kuaixiao.utils.StringUtil;
import com.ramos.kuaixiao.utils.ToastUtils;

import org.apache.http.Header;
import org.apache.http.entity.ByteArrayEntity;
import org.json.JSONException;
import org.json.JSONObject;

public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private final static String TAG = "LoginActivity";
    Button mLoginBtn;
    Button mRegisterBtn;
    EditText mUserTxt;
    EditText mDealerTxt;
    EditText mPwdTxt;
    Spinner logintype;
    private Context mContext;
    public final static int UPLOAD_SUCCESS = 100;
    public final static int UPLOAD_FAIL = 101;
    private String mDealerName;
    private String mUserName;
    private String mPsWd;
    private CheckBox mCheckBox;
    private CommonLoading loading;
    ImageView mShowView;
    private boolean mIsShowPwd = false;
    StartLocation startLocation;
    private LocationManager lm;//【位置管理】
    private String mLoginName;
    private boolean mIsChoosed = false;
    ArrayAdapter adapter;
    int loginType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "App.isOldVersion:" + SharedPreference.hasPreferString("isOldVersion") + ","+App.isOldVersion);
        if (!StringUtil.isEmpty(SharedPreference.getPreferString("password"))) {
            if (SharedPreference.getPreferString("type").equals("10")) {
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                finish();
            } else if (SharedPreference.getPreferString("type").equals("20")) {
                startActivity(new Intent(LoginActivity.this, OrderMainActivity.class));
                finish();
            }else if (SharedPreference.getPreferString("type").equals("11")) {
                startActivity(new Intent(LoginActivity.this, DriverMainActivity.class));
                finish();
            }
        } else {
            mLoginName = SharedPreference.getPreferString("id");
            setContentView(R.layout.activity_login_test);
            mContext = this;
            initView();
            checkGPS();
            startLocation = new StartLocation(this);
            startLocation.startLocation();
            getPermission();
        }

    }

    private void checkGPS() {
        lm = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean ok = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (ok) {//开了定位服务
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                // 没有权限，申请权限。
                //Toast.makeText(getActivity(), "没有权限", Toast.LENGTH_SHORT).show();

            } else {
                // 有权限了，去放肆吧。
                // Toast.makeText(getActivity(), "有权限", Toast.LENGTH_SHORT).show();
            }
        } else {
            //Toast.makeText(getActivity(), "系统检测到未开启GPS定位服务", Toast.LENGTH_SHORT).show();
            ToastUtils.show("系统检测到未开启GPS定位服务");
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, 1315);
        }
    }

    private void getPermission() {
        //这段话 的意思   如果读的权限没有授权
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                ) {
            //就跳到让用户选择是否授权  给个码走返回方法
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA
                            , Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001);
        }
    }

    //当我申请权限的时候,调用
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //如果用户选择了同意授权     走我的方法
        if (requestCode == 1001) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            } else {
                ToastUtils.show("权限拒绝");
            }
        }
    }

    private void initView() {
        mUserTxt = (EditText) findViewById(R.id.et_username);
        mPwdTxt = ((EditText) findViewById(R.id.et_password));
        mDealerTxt = ((EditText) findViewById(R.id.et_dealer));
        mLoginBtn = (Button) findViewById(R.id.login_loginbutton);
        mLoginBtn.setOnClickListener(this);
        mRegisterBtn = (Button) findViewById(R.id.register_button);
        mRegisterBtn.setOnClickListener(this);

        mShowView = (ImageView) findViewById(R.id.eley_ig);
        mShowView.setOnClickListener(this);

        logintype = (Spinner) findViewById(R.id.logintype);
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.logintype));
        adapter.setDropDownViewResource(android.R.layout.select_dialog_item);
        logintype.setAdapter(adapter);
        logintype.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == 0) {
                    mDealerTxt.setVisibility(View.VISIBLE);
                    loginType = 0;
                } else if(i == 1){
                    mDealerTxt.setVisibility(View.GONE);
                    loginType = 1;
                }else if(i == 2){
                    mDealerTxt.setVisibility(View.GONE);
                    loginType = 2;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
            /*@Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(i == 0){
                    mDealerTxt.setVisibility(View.VISIBLE);
                    loginType = 0 ;
                } else {
                    mDealerTxt.setVisibility(View.GONE);
                    loginType = 1  ;
                }
            }*/
        });
        mPwdTxt.setTransformationMethod(PasswordTransformationMethod.getInstance());
        this.mPwdTxt.setSelection(mPwdTxt.length());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_loginbutton:
                checkLogin();
                break;
            case R.id.register_button:
                register();
                break;
            case R.id.eley_ig:
                showPwd();
                break;

        }
    }

    private void register() {
        startActivity(new Intent(this, EditUserInfoActivity.class));
    }

    private void showPwd() {
        if (mIsShowPwd) {
            mIsShowPwd = false;
            mPwdTxt.setTransformationMethod(PasswordTransformationMethod.getInstance());
            this.mPwdTxt.setSelection(mPwdTxt.length());
            mShowView.setImageResource(R.drawable.bt_faxian_n);
        } else {
            mIsShowPwd = true;
            mPwdTxt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            mPwdTxt.setSelection(mPwdTxt.length());
            mShowView.setImageResource(R.drawable.bt_faxian_h);
        }
    }

    private void checkLogin() {
        if (loginType == 0 && StringUtil.isEmpty(mDealerTxt.getText().toString())) {
            ToastUtils.showShort(mContext, "请输入分销商名称");
            return;
        }
        if (StringUtil.isEmpty(mUserTxt.getText().toString())) {
            ToastUtils.showShort(mContext, "请输入账号");
            return;
        }
        if (StringUtil.isEmpty(mPwdTxt.getText().toString())) {
            ToastUtils.showShort(mContext, "请输入密码");
            return;
        }
        mDealerName = mDealerTxt.getText().toString();
        mUserName = mUserTxt.getText().toString();
        mPsWd = mPwdTxt.getText().toString();
        if (loginType == 0) {
            getTask(mDealerName + "_" + mUserName, mPsWd, typeToInt(logintype.getSelectedItem().toString()));
        } else {
            getTask(mUserName, mPsWd, typeToInt(logintype.getSelectedItem().toString()));
        }
    }

    private int typeToInt(String s) {
        if (s.equals("业务员")) {
            return 1;
        } else if (s.equals("商店端")) {
            return 2;
        }else if (s.equals("司机端")) {
            return 3;
        }
        return 1;
    }

    private void getTask(final String user, final String psw, int i) {
        try {
            String url = NetUtils.LOGIN;
            loading = new CommonLoading(this);
            loading.setLoadText("登陆中...");
            AsyncHttpClient client = new AsyncHttpClient(); // 创建异步请求的客户端对象
            // 创建请求参数的封装的对象
            client.setMaxRetriesAndTimeout(2, 5000);
            // 创建请求参数的封装的对象
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", user);
            jsonObject.put("password", psw);
            jsonObject.put("src", "APP");
            jsonObject.put("type", i);
            Log.d(TAG, "login " + url + " " + jsonObject.toString());
            ByteArrayEntity stringEntity = new ByteArrayEntity(jsonObject.toString().getBytes("UTF-8"));
            stringEntity.setContentType("application/json");
            // 执行post方法
            client.post(mContext, url, stringEntity, "application/json", new JsonHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) {
                    loading.dismiss();
                    CommUtil.d(mContext, TAG, "login " + responseBody.toString());
                    Log.d(TAG, "login " + responseBody.toString());
                    try {
                        if (responseBody.getInt("status") == 200) {
                            JSONObject user = responseBody.getJSONObject("data");
                            Log.d(TAG, "user " + user.getString("id") + " " + user.getString("dealer") + " " + user.getInt("type"));
                            if (user.has("id") && !StringUtil.isEmpty(user.getString("id"))) {
                                if (!StringUtil.isEmpty(SharedPreference.getPreferString("id"))) {
                                    if (!user.getString("id").contains(SharedPreference.getPreferString("id"))) {
                                        App.mUserChanged = true;
                                        ToastUtils.show("已切换账号，将重置数据");
                                        SharedPreference.setPreferInteger("isFirstLogin", 0);
                                        clearDB();
                                    } else {
                                        App.mUserChanged = false;
                                        //SharedPreference.setPreferInteger("isFirstLogin", 1);
                                    }
                                } else {
                                    App.mUserChanged = false;
                                    SharedPreference.setPreferInteger("isFirstLogin", 0);
                                }
                                Log.d(TAG, "login mUserChanged" + App.mUserChanged);
                                if (user.getInt("type") == 20) {
                                    SharedPreference.setPreferString("id", user.getString("id"));
                                    App.mUserId = user.getString("id");
                                } else if (user.getInt("type") == 10 || user.getInt("type") == 11) {
                                    String[] ids = user.getString("id").split("_");
                                    if (ids.length > 1) {
                                        String id = ids[1];
                                        SharedPreference.setPreferString("id", id);
                                        App.mUserId = id;
                                    } else {
                                        String id = ids[0];
                                        SharedPreference.setPreferString("id", id);
                                        App.mUserId = id;
                                    }
                                }
                            }

                            if (user.has("dealer") && !StringUtil.isEmpty(user.getString("dealer"))) {
                                SharedPreference.setPreferString("dealer", user.getString("dealer"));
                            }

                            if (user.has("org") && !StringUtil.isEmpty(user.getString("org"))) {
                                String[] ids = user.getString("org").split("_");
                                if (ids.length > 1) {
                                    String id = ids[1];
                                    SharedPreference.setPreferString("org", id);
                                } else {
                                    String id = ids[0];
                                    SharedPreference.setPreferString("org", id);
                                }
                            }

                            if (user.has("password") && !StringUtil.isEmpty(user.getString("password"))) {
                                SharedPreference.setPreferString("password", psw);
                            }

                            if (user.has("dealerName") && !StringUtil.isEmpty(user.getString("dealerName"))) {
                                SharedPreference.setPreferString("dealerName", user.getString("dealerName"));
                            }

                            if (user.has("orgName") && !StringUtil.isEmpty(user.getString("orgName"))) {
                                SharedPreference.setPreferString("orgName", user.getString("orgName"));
                            }

                            if (user.has("name") && !StringUtil.isEmpty(user.getString("name"))) {
                                SharedPreference.setPreferString("name", user.getString("name"));
                            }
                            if (user.has("company") && !StringUtil.isEmpty(user.getString("company"))) {
                                SharedPreference.setPreferString("company", user.getString("company"));
                            }
                            if (user.has("department") && !StringUtil.isEmpty(user.getString("department"))) {
                                SharedPreference.setPreferString("department", user.getString("department"));
                            }
                            if (user.has("phone") && !StringUtil.isEmpty(user.getString("phone"))) {
                                SharedPreference.setPreferString("phone", user.getString("phone"));
                            } else {
                                SharedPreference.setPreferString("phone", "");
                            }
                            if (user.has("email") && !StringUtil.isEmpty(user.getString("email"))) {
                                SharedPreference.setPreferString("email", user.getString("email"));
                            } else {
                                SharedPreference.setPreferString("email", "");
                            }
                            if (user.getInt("type") == 10) {
                                SharedPreference.setPreferString("type", "10");
                                ToastUtils.showShort(LoginActivity.this, "登陆成功");
                                startActivity(new Intent(LoginActivity.this, LoadingActivity.class));
                                finish();
                            } else if (user.getInt("type") == 20) {
                                SharedPreference.setPreferString("type", "20");
                                ToastUtils.showShort(LoginActivity.this, "登陆成功");
                                startActivity(new Intent(LoginActivity.this, OrderMainActivity.class));
                            } else if (user.getInt("type") == 11) {
                                SharedPreference.setPreferString("type", "11");
                                ToastUtils.showShort(LoginActivity.this, "登陆成功");
                                startActivity(new Intent(LoginActivity.this, DriverMainActivity.class));
                            } else {
                                ToastUtils.show("该用户没有登录权限");
                            }
                        } else {
                            sendMessagea(UPLOAD_FAIL, responseBody.getString("msg"));
                        }
                    } catch (JSONException e) {
                        sendMessagea(UPLOAD_FAIL, "登陆异常");
                        e.printStackTrace();
                    }
                }

                /* @Override
                 public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                     //loading.dismiss();
                     sendMessagea(UPLOAD_FAIL, "登陆异常");
                     throwable.printStackTrace();// 把错误信息打印出轨迹来
                 }*/
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                    super.onFailure(statusCode, headers, responseString, throwable);
                    loading.dismiss();
                    CommUtil.d(mContext, TAG, "login " + responseString.toString());
                    sendMessagea(UPLOAD_FAIL, "登陆异常");
                    throwable.printStackTrace();// 把错误信息打印出轨迹来
                }
            });
        } catch (Exception e) {
            loading.dismiss();
            sendMessagea(UPLOAD_FAIL, "登陆异常");
            e.printStackTrace();
        }
    }

    private void clearDB() {
        new AllCustomerDB().deleteAll();
        new AllCustomerStoreDB().deleteAll();
        new BrandDB().deleteAll();
        new BrandInfoDB().clearShopMall();
        new ClientPriceDB().deleteAll();
        new CustomerDB().deleteAll();
        new CustomerStoreDB().deleteAll();
        new CustomerWareHouseDB().deleteAll();
        new EmpBrandDB().deleteAll();
        new EmpStoreHouseDB().deleteAll();
        new OrderDB().deleteAll();
        new PriceDB().deleteAll();
        new PriceTypeDB().deleteAll();
        new SaleCustomerDB().deleteAll();
        new SaleCustomerStoreDB().deleteAll();
        new ShopsDB().deleteAll();
        new StoreNumDB().deleteAll();
        new UnSubmitOrderDB().deleteAll();
        new WareHouseDB().deleteAll();
    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPLOAD_SUCCESS:
                    ToastUtils.showShort(LoginActivity.this, "登陆成功");
                    finish();
                    startActivity(new Intent(LoginActivity.this, LoadingActivity.class));
                    break;
                case UPLOAD_FAIL:
                    ToastUtils.showShort(mContext, msg.obj.toString());
                    //startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    break;
                default:
                    break;
            }
        }
    };

    private void sendMessagea(int iWhat, Object obj) {
        Message msg = Message.obtain();
        msg.what = iWhat;
        msg.obj = obj;
        mHandler.sendMessage(msg);
    }
}
